﻿using HBS.InvokeSupport;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Newtonsoft.Json;
using PIMS.DBModel;
using PIMS.glb;
using PIMS.Models.Base;
using PIMS.ORM;
using PIMS.Utils;
using PIMS.WorkPlugin.Util;
using PIMS.XmlModel;
using PIMS_Interface.DBModel;
using PIMS_Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using WebApi.Models.AGV;
using WeifenLuo.WinFormsUI.Docking;

namespace PIMS
{
    /// <summary>
    /// 说明:
    /// </summary>
    public partial class FormMain : DockContent
    {
        string basePath = AppDomain.CurrentDomain.BaseDirectory;
        string overMsg = "";
        int lineCount = 0;
        string HandCreatOrder = string.Empty;//获取手动工单控件返回值
        bool isAutoWorkOrder = false;
        string plant = "";

        //反射过来的方法
        Assembly assemWorkPlugin = null;
        object sampleWorkOrderOperInstance = null;
        MethodInfo sampleWorkOrderOper_btn_Download = null;
        MethodInfo sampleWorkOrderOper_btn_Over = null;
        MethodInfo sampleWorkOrderOper_Timer1s_Tick = null;
        MethodInfo sampleWorkOrderOper_Timer3s_Tick = null;

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {

            if (Common.pimsConfig.GetAppValueByKey("IsAutoWorkOrder") == "1")
            {
                //this.btn_Add.Visible = false;
                //this.btn_Download.Visible = false;
                //this.btn_Over.Visible = false;
                //this.btnCancle.Visible = false;
                this.groupBox3.Visible = false;

                this.isAutoWorkOrder = true;
            }
            else
            {
                this.groupBox2.Visible = false;
            }

            new Thread(new ThreadStart(Thread_Init)) { IsBackground = true }.Start();

            //FreshData();

        }
        static DataTable dtBatchInfo = new DataTable();
        private void Thread_Init()
        {
            try
            {             
                int.TryParse(Common.pimsConfig.GetAppValueByKey("lineCount"), out lineCount);
                DataTable dtCurrent = SqlSugarHelper.QueryToDataTable<orderformcurrent>("1=1 order by id", lineCount);
                
                 //SqlSugarHelper.QueryToDataTable<batchInfoSync>("1=1", 10);
                DataTable dtEdit = dtCurrent.Clone();
                dtEdit.Rows.Add(dtEdit.NewRow());

                this.Invoke(
                new Action(() =>
                {
                    dtEdit.Rows.Add(dtEdit.NewRow());

                    DgvTools.AutoGenerateColumns(this.dgv, Common.orderformcurrentConfigX);
                    DgvTools.AutoGenerateColumns(this.dgvEdit, Common.orderformcurrentConfigX, new List<string>()
                    { "id","sendToPLC" });//,"packager"
                    DgvTools.AutoGenerateColumns(dgvAGV, Common.batchInfoSyncConfigX);

                    this.dgv.DataSource = dtCurrent;
                    dgvAGV.DataSource = GetSAPOrder();// dtBatchInfo;
                    //this.dgvEdit.AutoGenerateColumns = true;
                    //this.dgvEdit.DataSource = dt;
                    this.dgvEdit.DataSource = dtEdit;
                    //  this.dgvEdit.ReadOnly = true;
                    //   this.dgvEdit.Columns[0].CellType

                    DgvTools.dataGridView(this.dgv);
                    DgvTools.dataGridViewAutoSize(this.dgv);
                    DgvTools.dataGridViewDisableSort(this.dgv);
                    //this.dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

                    DgvTools.dataGridView(this.dgvEdit);
                    DgvTools.dataGridViewDisableSort(this.dgvEdit);
                    //  DgvTools.dataGridViewAutoSize(this.dgvEdit);

                    DgvTools.dataGridView(dgvAGV);
                    DgvTools.dataGridViewAutoSize(dgvAGV);
                    DgvTools.dataGridViewDisableSort(dgvAGV);

                    float fontSizeHead = Convert.ToSingle(Common.pimsConfig.GetAppValueByKey("dgvHeadFontSize"));
                    dgv.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", fontSizeHead, FontStyle.Regular, GraphicsUnit.Point, 134);
                    dgvEdit.ColumnHeadersDefaultCellStyle.Font = dgv.ColumnHeadersDefaultCellStyle.Font;

                    float fontSize = Convert.ToSingle(Common.pimsConfig.GetAppValueByKey("dgvFontSize"));
                    dgv.DefaultCellStyle.Font = new Font("宋体", fontSize, FontStyle.Regular, GraphicsUnit.Point, 134);
                    dgvEdit.DefaultCellStyle.Font = dgv.DefaultCellStyle.Font;

                    timer2.Enabled = true;
                    timer3.Enabled = true;

                }));

                while (!Common.initPlcOK)
                {
                    Thread.Sleep(100);
                }

                this.overMsg = Common.pimsConfig.GetAppValueByKey("overMsg");
                //利用反射机制将步骤名称与对应方法映射
                // Type t = typeof(fullClassName);
                assemWorkPlugin = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "Plugins\\PIMS_WorkPlugin.dll");
                Type t = assemWorkPlugin.GetType(Common.pimsConfig.GetAppValueByKey("workOrderOper"));
                sampleWorkOrderOperInstance = Activator.CreateInstance(t, null);
                MethodInfo sampleWorkOrderOper_Init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
                sampleWorkOrderOper_btn_Download = t.GetMethod("btn_Download", BindingFlags.Instance | BindingFlags.Public);
                sampleWorkOrderOper_btn_Over = t.GetMethod("btn_Over", BindingFlags.Instance | BindingFlags.Public);
                sampleWorkOrderOper_Timer1s_Tick = t.GetMethod("Timer1s_Tick", BindingFlags.Instance | BindingFlags.Public);
                sampleWorkOrderOper_Timer3s_Tick = t.GetMethod("Timer3s_Tick", BindingFlags.Instance | BindingFlags.Public);

                sampleWorkOrderOper_Init.Invoke(sampleWorkOrderOperInstance, new object[]
                {
                    Common.d,
                    Common.log,
                    Common.allPLC,
                    Common.orderformcurrentConfigX,
                    this.dgv,
                    dgvAGV,
                    //Common.pimsConfig.GetAppValueByKey("IsAutoWorkOrder") == "1",
                    //Convert.ToInt16(Common.pimsConfig.GetAppValueByKey("lineCount")),
                    Common.pimsConfig
                });

            }
            catch (Exception ex)
            {
                Common.d.DebugMsg(ex.Message, InfoLevel.error);
                Common.log.Error(ex.Message, ex);
            }
        }

        public void ClearLog()
        {

        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.当前时间.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (String.IsNullOrEmpty(Common.UserLogin.UserName))
            {
                this.登陆状态.Text = "登陆状态:" + "未登陆";
                this.登陆状态.ForeColor = Color.Black;
            }
            else
            {
                this.登陆状态.Text = "登陆状态:" + Common.UserLogin.UserName + "/" + "班组:" + Common.UserLogin.Department;
                this.登陆状态.ForeColor = Color.Green;
            }

        }

        private void btn_User_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.ShowDialog();
            if (frmLogin.DialogResult == DialogResult.OK)
            {
                //返回登陆对话框的结果
                Common.UserLogin = frmLogin.UserLogin;
                if (String.IsNullOrEmpty(Common.UserLogin.UserName))
                {
                    this.btn_Add.Enabled = false;
                    this.btn_Download.Enabled = false;
                    this.btn_Over.Enabled = false;
                    this.btnCancle.Enabled = false;
                    this.btn_handCrOrd.Enabled = false;
                    this.btn_AddInfo.Enabled = false;
                    this.btn_Check.Enabled = false;
                    this.btnManualWMS.Enabled = false;
                }
                else
                {
                    this.btn_Add.Enabled = true;
                    this.btn_Download.Enabled = true;
                    this.btn_Over.Enabled = true;
                    this.btnCancle.Enabled = true;
                    //if (Common.UserLogin.Level == "9")
                    //{
                    //    btn_handCrOrd.Visible = true;
                    //}
                    //else
                    //{
                    //    btn_handCrOrd.Visible = false;
                    //}
                    this.btn_handCrOrd.Enabled = true;
                    this.btn_AddInfo.Enabled = true;
                    this.btn_Check.Enabled = true;
                    this.btnManualWMS.Enabled = true;
                    //string regkeypath = @"SOFTWARE\PIMS\FormMain";
                    //RegistryTool.WriteReg(regkeypath, "LoginUserName", Common.UserLogin.UserName);
                }
                Common.ActionUserChange.BeginInvoke(Common.UserLogin.Level, null, null);
            }
            frmLogin.Dispose();
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            string packager = this.dgvEdit.Rows[0].Cells["packager"].Value.ToString();
            //string packager = this.dgvEdit.Rows[0].Cells[0].Value.ToString();
            if (String.IsNullOrEmpty(packager))
            {
                MessageBox.Show("待添加区为空！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                int index = dgvEdit.CurrentRow.Index;
                int rowIndex = -1;
                //int pid = -1;
                if (packager.Contains("西线"))
                    rowIndex = 0;
                else if (packager.Contains("东线"))
                    rowIndex = 1;    

                //for (int i = 0; i < this.dgv.RowCount; i++)
                //{
                //    if (pid == Convert.ToInt32(this.dgv.Rows[i].Cells["id"].Value))
                //    {
                //        rowIndex = i;
                //        break;
                //    }
                //}
                if (rowIndex == -1)
                {
                    MessageBox.Show(string.Format("未找到匹配的产线:{0}！", packager), "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (!string.IsNullOrEmpty(this.dgv.Rows[rowIndex].Cells["workOrder"].Value.ToString()))
                {
                    MessageBox.Show(String.Format("此订单为<{0}>号生产线订单，请先结束<{0}>号生产线订单，再添加！\r\n工单号:{1}",
                        this.dgv.Rows[rowIndex].Cells["id"].Value.ToString(),
                        this.dgv.Rows[rowIndex].Cells["workOrder"].Value.ToString()),
                        "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    for (int i = 0; i < dgvEdit.ColumnCount ; i++)
                    {
                        this.dgv.Rows[rowIndex].Cells[this.dgv.Columns[i + 2].Name].Value =
                            dgvEdit.Rows[index].Cells[dgvEdit.Columns[i].Name].Value.ToString();
                    }
                    //this.dgv.Rows[rowIndex].Cells["reserved4"].Value = "1";

                    //保存产线订单信息
                    Common.SaveCurrentOrderForm(this.dgv);
                    ////删除加载到产线的订单-用生产订单号索引
                    //string where = string.Format("code_b='{0}'", dgvAGV.Rows[index].Cells["code_b"].Value.ToString());
                    //SqlSugarHelper.DeleteRecord<batchInfoSync>(where);
                    //清空待添加订单表
                    for (int i = 0; i < this.dgvEdit.ColumnCount; i++)
                    {
                        this.dgvEdit[i, 0].Value = string.Empty;
                    }

                    string msg = "";
                    msg = string.Format("添加工单成功！工单号:{0}", this.dgv.Rows[rowIndex].Cells["workOrder"].Value.ToString());
                    Common.d.DebugMsg(msg);
                    Common.log.Info(msg);
                    MessageBox.Show(msg, "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //if (this.dgv.Columns.Contains("productName"))
                }
            }
            catch (Exception ex)
            {
                Common.d.DebugMsg(ex.Message, InfoLevel.error);
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Common.log.Error("", ex);
            }
        }

        private void btn_Download_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridViewRow currentRow = this.dgv.CurrentRow;
                if (currentRow == null)
                {
                    MessageBox.Show("请先选择要投放的产线再执行本操作!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                int id = currentRow.Index;
                DataTable dt = (DataTable)this.dgv.DataSource;
                orderformcurrent current = DatatableToEntity.FillModel<orderformcurrent>(dt.Rows[id] /*, Common.orderformcurrentConfigX*/);

                string orderNo = current.workOrder;
                string device = current.packager;
                string batchNo = current.batchNo;
                int productID = current.id;
                if (String.IsNullOrEmpty(orderNo))
                {
                    MessageBox.Show(String.Format("请确认当前选中的工单是否存在！"), "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (current.sendToPLC == "1")
                {
                    MessageBox.Show(String.Format("该订单已下发至产线，请勿重复操作?\r\n产线号:{0}\r\n工单号:{1}\r\n批次:{2}",
                        productID, orderNo, batchNo), "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    if (MessageBox.Show(String.Format("确定下发工单数据至设备?\r\n产线号:{0}\r\n工单号:{1}\r\n批次:{2}",
                        productID, orderNo, batchNo), "注意", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
                        return;

                    //反射调用btn_Download
                    //ProxyObject po = new ProxyObject();
                    //po.assembly = Assembly.GetExecutingAssembly();
                    //bool ret=(bool)po.InvokeMethod(Common.pimsConfig.GetAppValueByKey("workOrderOper"), "btn_Download", 
                    //    new object[] { current });
                    bool ret = (bool)sampleWorkOrderOper_btn_Download.Invoke(sampleWorkOrderOperInstance,
                                                   new object[] { current }); //调用反射函数
                    if (ret)
                    {

                        //if (Common.workOrderColMapDict.ContainsKey("sendToPLC"))
                        //{
                        this.dgv.Rows[id].Cells["sendToPLC"].Value = "1";
                        //this.dgv.Rows[id].Cells["reserved11"].Value = DateTime.Now.ToString("yyyy-MM-dd");
                        Common.SaveCurrentOrderForm(this.dgv);
                        //}

                        string msg = string.Format("工单下发成功！产线：{0},工单号：{1},批次：{2}", productID, orderNo, batchNo);
                        Common.d.DebugMsg(msg);
                        Common.log.Info(msg);
                        MessageBox.Show(msg, "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        string msg = string.Format("工单下发失败！产线：{0},工单号：{1},批次：{2}", productID, orderNo, batchNo);
                        Common.d.DebugMsg(msg, InfoLevel.warring);
                        Common.log.Info(msg);
                        MessageBox.Show("工单下发失败！", "Err", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Common.d.DebugMsg(ex.Message, InfoLevel.error);
                MessageBox.Show(ex.Message, "NG", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Common.log.Error("", ex);
            }
        }

        private void btn_Over_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridViewRow currentRow = this.dgv.CurrentRow;
                if (currentRow == null)
                {
                    MessageBox.Show("请先选择要结束的产线再执行本操作!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                int id = currentRow.Index;
                DataTable dt = (DataTable)this.dgv.DataSource;
                orderformcurrent current = DatatableToEntity.FillModel<orderformcurrent>(dt.Rows[id] /*, Common.orderformcurrentConfigX*/);
                string orderNo = current.workOrder;
                string device = current.packager;
                if (String.IsNullOrEmpty(orderNo))
                {
                    MessageBox.Show("请确认当前选中工单是否存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (MessageBox.Show(this.overMsg, "注意", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
                    return;

                //反射调用btn_Download
                //ProxyObject po = new ProxyObject();
                //po.assembly = Assembly.GetExecutingAssembly();
                //bool ret = (bool)po.InvokeMethod(Common.pimsConfig.GetAppValueByKey("workOrderOper"), "btn_Over",
                //    new object[] { current });
                bool ret = (bool)sampleWorkOrderOper_btn_Over.Invoke(sampleWorkOrderOperInstance,
                                    new object[] { current }); //调用反射函数
                if (ret)
                {
                    string msg = string.Format("结束工单 工单号：{0}", orderNo);
                    Common.d.DebugMsg(msg);
                    Common.log.Info(msg);

                    Common.SaveCurrentOrderToHistory(orderNo);
                    //清空订单行 保留序号和包装设备
                    for (int i = 1; i < this.dgv.ColumnCount; i++)
                    {
                        if(!dgv[i, id].Value.ToString().Contains("西线")&& !dgv[i, id].Value.ToString().Contains("东线"))
                            this.dgv[i, id].Value = string.Empty;
                    }
                    Common.SaveCurrentOrderForm(this.dgv);
                }
                else
                {
                    string msg = string.Format("结束工单失败 设备：{0}，工单号：{1}", device, orderNo);
                    Common.d.DebugMsg(msg, InfoLevel.warring);
                }

            }
            catch (Exception ex)
            {
                Common.d.DebugMsg(ex.Message, InfoLevel.error);
                MessageBox.Show(ex.Message, "NG", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Common.log.Error("", ex);
            }
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridViewRow currentRow = this.dgv.CurrentRow;
                if (currentRow == null)
                {
                    MessageBox.Show("请先选择要取消的产线再执行本操作!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                int id = currentRow.Index;
                DataTable dt = (DataTable)this.dgv.DataSource;
                orderformcurrent current = DatatableToEntity.FillModel<orderformcurrent>(dt.Rows[id] /*, Common.orderformcurrentConfigX*/);
                string orderNo = current.workOrder;
                if (String.IsNullOrEmpty(orderNo))
                {
                    MessageBox.Show("请确认当前选中工单是否存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (current.sendToPLC == "1")
                {
                    MessageBox.Show("已下发的工单不能取消！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (MessageBox.Show(String.Format("确定要取消工单吗？\r\n工单号：{0}",
                    orderNo), "注意", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
                    return;

                //清空订单行 保留序号和包装设备
                for (int i = 2; i < this.dgv.ColumnCount; i++)
                {
                    if (!dgv[i, id].Value.ToString().Contains("西线") && !dgv[i, id].Value.ToString().Contains("东线"))
                        this.dgv[i, id].Value = string.Empty;
                }
                Common.SaveCurrentOrderForm(this.dgv);
            }
            catch (Exception ex)
            {
                Common.d.DebugMsg(ex.Message, InfoLevel.error);
                MessageBox.Show(ex.Message, "NG", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Common.log.Error("", ex);
            }
        }      

        /// <summary>
        /// 根据反射动态加载DLL插件
        /// 传值格式是DataTable
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Edit_Click(object sender, EventArgs e)
        {
            try
            {
                //#region 查询SAP订单信息
                //dgvAGV.DataSource = GetSAPOrder();
                //DgvTools.dataGridView(dgvAGV);
                //DgvTools.dataGridViewAutoSize(dgvAGV);
                //DgvTools.dataGridViewDisableSort(dgvAGV);
                ////FreshData();
                //#endregion
                //return;

                //assemWorkPlugin = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "Plugins\\PIMS_WorkPlugin.dll");

                string formEditName = Common.pimsConfig.GetAppValueByKey("formEditName");
                Type t = assemWorkPlugin.GetType(formEditName);
                object obj = Activator.CreateInstance(t, null);
                t.InvokeMember("Init", BindingFlags.InvokeMethod, null, obj, new object[] {
                    Common.d,
                    Common.log
                });
                t.InvokeMember("ShowDialog", BindingFlags.InvokeMethod, null, obj, new object[] { });
                t.InvokeMember("Close", BindingFlags.InvokeMethod, null, obj, new object[] { });
                orderformcurrent order = (orderformcurrent)t.InvokeMember("RetValue", BindingFlags.GetProperty, null, obj, null);
                t.InvokeMember("Dispose", BindingFlags.InvokeMethod, null, obj, new object[] { });
                if (order != null)
                {
                    DataTable dt = DynamicObjectHelper.ConvertToDataTableWithData(
                         DynamicObjectHelper.ConvertToDynamic(order));
                    this.dgvEdit.DataSource = dt;
                    //this.btn_Add_Click(null, null);
                }

                if (this.isAutoWorkOrder)
                {
                    DataTable dtCurrent = SqlSugarHelper.QueryToDataTable<orderformcurrent>("1=1", lineCount);
                    this.dgv.DataSource = dtCurrent;
                }
            }
            catch (Exception ex)
            {
                Common.log.Error("", ex);
                MessageBox.Show(ex.Message, "NG", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void btn_AddInfo_Click(object sender, EventArgs e)
        {
            DataGridViewRow currentRow = this.dgv.CurrentRow;
            if (currentRow == null)
            {
                MessageBox.Show("请先选择要修改的工单!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int index = dgv.CurrentCell.RowIndex;
            string packager = this.dgv.Rows[index].Cells["sendToPLC"].Value.ToString();
            FormSuppleInfo formSuppleInfo = new FormSuppleInfo();
            Common.bSendPLC = packager == "1" ? true : false;
            formSuppleInfo.txtBatch.Text = this.dgv.Rows[index].Cells["batchNo"].Value.ToString();
            formSuppleInfo.txtListNum.Text = this.dgv.Rows[index].Cells["reserved5"].Value.ToString();
            formSuppleInfo.txtBatchRule.Text = this.dgv.Rows[index].Cells["reserved3"].Value.ToString();
            formSuppleInfo.cbxPalRule.Text = this.dgv.Rows[index].Cells["reserved4"].Value.ToString();
            formSuppleInfo.txtProductStage.Text = this.dgv.Rows[index].Cells["reserved8"].Value.ToString();
            formSuppleInfo.txtQulityInfo.Text = this.dgv.Rows[index].Cells["reserved9"].Value.ToString();
            formSuppleInfo.txtProductLevel.Text = this.dgv.Rows[index].Cells["reserved10"].Value.ToString();
            formSuppleInfo.txtPecoalNote.Text = this.dgv.Rows[index].Cells["reserved11"].Value.ToString();
            formSuppleInfo.txtPecialInfo.Text = this.dgv.Rows[index].Cells["reserved7"].Value.ToString();
            formSuppleInfo.txtReclaimLogo.Text = this.dgv.Rows[index].Cells["reserved6"].Value.ToString();
            formSuppleInfo.ShowDialog();
            if (formSuppleInfo.DialogResult == DialogResult.OK)
            {

                this.dgv.Rows[index].Cells["batchNo"].Value = formSuppleInfo.txtBatch.Text;
                this.dgv.Rows[index].Cells["reserved5"].Value = formSuppleInfo.txtListNum.Text;
                this.dgv.Rows[index].Cells["reserved3"].Value = formSuppleInfo.txtBatchRule.Text;
                this.dgv.Rows[index].Cells["reserved4"].Value = formSuppleInfo.cbxPalRule.Text;
                this.dgv.Rows[index].Cells["reserved8"].Value = formSuppleInfo.txtProductStage.Text;
                this.dgv.Rows[index].Cells["reserved9"].Value = formSuppleInfo.txtQulityInfo.Text;
                this.dgv.Rows[index].Cells["reserved10"].Value = formSuppleInfo.txtProductLevel.Text;
                this.dgv.Rows[index].Cells["reserved11"].Value = formSuppleInfo.txtPecoalNote.Text;
                this.dgv.Rows[index].Cells["reserved7"].Value = formSuppleInfo.txtPecialInfo.Text;
                this.dgv.Rows[index].Cells["reserved6"].Value = formSuppleInfo.txtReclaimLogo.Text;
                Common.SaveCurrentOrderForm(this.dgv);
            }
            formSuppleInfo.Dispose();
        }

        private void btn_Check_Click(object sender, EventArgs e)
        {
            DataGridViewRow currentRow = this.dgv.CurrentRow;
            int index = dgv.CurrentCell.RowIndex;
            if (currentRow == null)
            {
                MessageBox.Show("请先选择要检查的产线再执行本操作!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            MessageBox.Show(this.dgv.Rows[index].Cells["productName"].Value.ToString()
                    + " " + this.dgv.Rows[index].Cells["productMark"].Value.ToString()
                    + " " + this.dgv.Rows[index].Cells["batchNo"].Value.ToString()
                    + " " + this.dgv.Rows[index].Cells["reserved5"].Value.ToString()
                    + " " + this.dgv.Rows[index].Cells["reserved7"].Value.ToString() +
                    "\r\n 喷码信息如果有误，请修改生成喷码信息的相关项，不可直接修改喷码信息", "生成的喷码信息");
        }

        /// <summary>
        /// 自动调整ListView列宽
        /// </summary>
        /// <param name="lv1"></param>
        /// <param name="msg"></param>
        public void AutoUpdateMaxWidth(ListView lv1, string msg)
        {
            int multi = 5;
            if (msg.Length * multi > lv1.Columns[0].Width)
            {
                lv1.Columns[0].Width = (msg.Length + 1) * multi;
            }
        }

        /// <summary>
        /// 1S定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            string oldMsg = "";
            try
            {
                if (sampleWorkOrderOper_Timer1s_Tick != null)
                    sampleWorkOrderOper_Timer1s_Tick.Invoke(sampleWorkOrderOperInstance, null);
            }
            catch (Exception ex)
            {
                if (oldMsg != ex.Message)
                {
                    Common.d.DebugMsg(ex.Message);
                    oldMsg = ex.Message;
                }
                Common.log.Error("", ex);
            }
        }

        /// <summary>
        /// 3S定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer3_Tick(object sender, EventArgs e)
        {
            string oldMsg = "";
            try
            {
                if (sampleWorkOrderOper_Timer3s_Tick != null)
                    sampleWorkOrderOper_Timer3s_Tick.Invoke(sampleWorkOrderOperInstance, null);
            }
            catch (Exception ex)
            {
                if (oldMsg != ex.Message)
                {
                    Common.d.DebugMsg(ex.Message);
                    oldMsg = ex.Message;
                }
                Common.log.Error("", ex);
            }
        }

        private void FormMain_Resize(object sender, EventArgs e)
        {
            //this.groupBox1.Width = panelButton.Width - 10;
            //this.groupBox1.Height = this.Height - panelButton.Height -20;
            //this.groupBox3.Width = panelButton.Width - 10;

            this.groupBox1.Width = panelButton.Width - 10;
            //this.groupBox1.Height = this.Height - panelButton.Height -20;
            this.groupBox3.Width = panelButton.Width - 10;

            this.groupBox2.Width = panelButton.Width - 10;
            //   this.groupBox2.Height = this.Height - 10;

            //if (this.groupBox2.Visible)
            //{
            //    if (Convert.ToInt16(Common.pimsConfig.GetAppValueByKey("lineCount")) <= 5)
            //    {
            //        this.groupBox1.Height = 174;
            //    }
            //    else
            //    {
            //        this.groupBox1.Height = 280;
            //    }
            //}
            //else
            //{
            //    this.groupBox1.Width = panelButton.Width - 10;
            //    this.groupBox1.Height = this.Height - panelButton.Height - 20;
            //    this.groupBox1.Height = this.Height - panelButton.Height - 20;
            //}

            //this.groupBox3.Width = this.panelButton.Width - 10;

        }

        private void btnManualWMS_Click(object sender, EventArgs e)
        {
            
            try
            {
                string formEditName = Common.pimsConfig.GetAppValueByKey("formManualWMS");
                Type t = assemWorkPlugin.GetType(formEditName);
                object obj = Activator.CreateInstance(t, null);

                t.InvokeMember("Init", BindingFlags.InvokeMethod, null, obj, new object[] { Common.d, Common.log });
                t.InvokeMember("ShowDialog", BindingFlags.InvokeMethod, null, obj, new object[] { });
                t.InvokeMember("Close", BindingFlags.InvokeMethod, null, obj, new object[] { });
                ////orderformcurrent order = (orderformcurrent)t.InvokeMember("RetValue", BindingFlags.GetProperty, null, obj, null);
                t.InvokeMember("Dispose", BindingFlags.InvokeMethod, null, obj, new object[] { });
                
                
            }
            catch (Exception ex)
            {
                Common.log.Error("", ex);
                MessageBox.Show(ex.Message, "NG", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        
        public static void FreshData()
        {
            DataTable dtBatchInfonew = SqlSugarHelper.QueryToDataTable<batchInfoSync>("isUpdate = 0");

            if (dtBatchInfo.Rows == dtBatchInfonew.Rows)
                return;
            dtBatchInfo = dtBatchInfonew;
            //dgvAGV.Invoke(new Action(() =>{dgvAGV.DataSource = dtBatchInfo; }));   
        }

        public DataTable GetSAPOrder()
        {
            dtBatchInfo = SqlSugarHelper.QueryToDataTable<batchInfoSync>("select * from tb_batchInfoSync where isUpdate is false  ");
            for (int i = 0; i < dtBatchInfo.Rows.Count; i++)
            {
                if(!string.IsNullOrEmpty(dtBatchInfo.Rows[i][2].ToString()) && Enums.工厂.ContainsKey(dtBatchInfo.Rows[i][2].ToString()) )
                    dtBatchInfo.Rows[i][2] = Enums.工厂[dtBatchInfo.Rows[i][2].ToString()];
                if (!string.IsNullOrEmpty(dtBatchInfo.Rows[i][1].ToString()) && Enums.工作中心.ContainsKey(dtBatchInfo.Rows[i][1].ToString()))
                    dtBatchInfo.Rows[i][1] = Enums.工作中心[dtBatchInfo.Rows[i][1].ToString()];
                if (!string.IsNullOrEmpty(dtBatchInfo.Rows[i][12].ToString()) && Enums.订单类型.ContainsKey(dtBatchInfo.Rows[i][12].ToString()))
                    dtBatchInfo.Rows[i][12] = Enums.订单类型[dtBatchInfo.Rows[i][12].ToString()];
            }
            return dtBatchInfo;  
        }
    }
}
